package com.shide.common.util;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class IDUtils {

    public static void main(String[] args) {
        long snowflake = IdUtil.getSnowflakeNextId();
        System.out.println(snowflake);
        Snowflake snowflake1 = IdUtil.getSnowflake(1, 1);

    }

    /**
     * 生成18位唯一无序数字
     */
    public static String generateUniqueId() {
        try {
            // 生成UUID
            UUID uuid = UUID.randomUUID();

            // 获取UUID的字节数组
            ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
            bb.putLong(uuid.getMostSignificantBits());
            bb.putLong(uuid.getLeastSignificantBits());
            byte[] uuidBytes = bb.array();

            // 使用SHA-256对UUID字节数组进行哈希处理
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(uuidBytes);

            // 将哈希值转换为正整数
            long hashNumber = 0;
            for (int i = 0; i < 8; i++) {
                hashNumber = (hashNumber << 8) | (hash[i] & 0xff);
            }

            // 将哈希值转换为字符串
            String hashString = Long.toString(Math.abs(hashNumber));

            // 截取前18位
            return hashString.length() > 18 ? hashString.substring(0, 18) : String.format("%018d", Long.parseLong(hashString));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error generating unique ID", e);
        }
    }
}
